import { printLabelApi } from "@/api/common";
import { cancelBatchOrderShipmentApi } from "@/api/waybillManagement/businessWaybill";
import { getListApi, stockManagementExportApi } from "@/api/waybillManagement/stockManagement";
import CommonHook from "@/hook/commonHook";
import dayjs from "dayjs";
import { computed } from "vue";
import printJs from "print-js";
import { message, message as Message } from "ant-design-vue";
import { customsClearanceApi, pushOrdersTttxApi } from "@/api/waybillManagement/customerServiceWaybill";
export default function OperationHook(state: Base.GeneraDataType) {
  const {
    searchForm,
    tableData,
    drawerOpts,
    loading,
    activeKey,
    //  pageStat,
    tableRef,
    dialogOpts
  } = state;
  const selectRows = computed<Array<StockManagement.ListRows>>(() => {
    return tableRef.value.xTable.getCheckboxRecords() || [];
  });
  const {
    //  getNoZeroKey,
    downloadFileByBlob
  } = CommonHook();
  const getData = async () => {
    const params = {
      ...getParams(),
      statusList: activeKey.value === "-1" ? [1, 2, 3, 4] : [Number(activeKey.value)]
    };
    loading.value = true;
    tableData.value = [];
    return getListApi(params)
      .then((res: any) => {
        const { code, data } = res;
        if (code === 200) {
          tableData.value = data.records || [];
          searchForm.total = Number(data.total);
        }
      })
      .finally(() => {
        loading.value = false;
      });
  };

  // 创建工单
  const createWorkOrderHandle = () => {
    if (!selectRows.value.length) return Message.error("请勾选运单!");
    dialogOpts.title = `创建工单`;
    dialogOpts.width = "520px";
    dialogOpts.component = "CreateWorkOrder";
    dialogOpts.passData = selectRows.value;
    dialogOpts.visible = true;
  };
  // const pageStateic = () => {
  //   const params = getParams();
  //   return getPageStaticApi({ ...params, statusList: [1, 2, 3, 4] }).then((res: any) => {
  //     const { code, data } = res;
  //     if (code === 200) {
  //       Object.assign(pageStat.value, {
  //         "3": data[1],
  //         "4": data[2],
  //         "-1": data[3]
  //       });
  //       activeKey.value = String(getNoZeroKey(pageStat.value, ["3", "4", "-1"]));
  //     }
  //   });
  // };
  const getParams = () => {
    const {
      preOrderNoList,
      waybillNumList,
      fbaNumberList,
      bizIdList,
      storageBy,
      shortName,
      makeInvoiceStatus,
      shippingMethod,
      driverUserIdList,
      orderTimeList,
      expectedPickupTimeList,
      customerIdList,
      pageNum,
      pageSize,
      companyIdList,
      warehouseCodeList,
      channelIdList,
      pushOrderSuccess
    } = searchForm;
    const params: any = {
      preOrderNoList: [],
      waybillNumList: [],
      fbaNumberList: [],
      bizIdList,
      storageBy,
      shortName,
      makeInvoiceStatus,
      shippingMethod,
      driverUserIdList,
      customerIdList,
      orderTimeList: orderTimeList.length ? [dayjs(orderTimeList[0]).format("YYYY-MM-DD HH:mm:ss"), dayjs(orderTimeList[1]).format("YYYY-MM-DD HH:mm:ss")] : [],
      expectedPickupTimeList: expectedPickupTimeList.length ? [dayjs(expectedPickupTimeList[0]).format("YYYY-MM-DD HH:mm:ss"), dayjs(expectedPickupTimeList[1]).format("YYYY-MM-DD HH:mm:ss")] : [],
      pageNum,
      pageSize,
      companyIdList,
      warehouseCodeList,
      channelIdList,
      pushOrderSuccess
    };
    if (waybillNumList)
      params.waybillNumList = waybillNumList
        .trim()
        .replace(/,{1,}|，{1,}|\+{1,}|\s{1,}/g, ",")
        .split(",");
    if (preOrderNoList)
      params.preOrderNoList = preOrderNoList
        .trim()
        .replace(/,{1,}|，{1,}|\+{1,}|\s{1,}/g, ",")
        .split(",");
    if (fbaNumberList)
      params.fbaNumberList = fbaNumberList
        .trim()
        .replace(/,{1,}|，{1,}|\+{1,}|\s{1,}/g, ",")
        .split(",");
    if (channelIdList.length) {
      params.channelIdList = channelIdList.map((t: any) => t[t.length - 1]);
    }
    return params;
  };
  const searchHandle = async () => {
    searchForm.pageNum = 1;
    // await pageStateic();
    getData();
  };
  const changeTabHandle = () => {
    getData();
  };
  const editHandle = (row: StockManagement.ListRows) => {
    drawerOpts.title = `编辑(${row.preOrderNo})`;
    drawerOpts.width = "1200px";
    drawerOpts.type = 2;
    drawerOpts.component = "Details";
    drawerOpts.passData = row;
    drawerOpts.visible = true;
  };
  const showHandle = (row: StockManagement.ListRows) => {
    drawerOpts.title = `查看(${row.waybillNum})`;
    drawerOpts.width = "1200px";
    drawerOpts.type = 1;
    drawerOpts.component = "Details";
    drawerOpts.passData = row;
    drawerOpts.visible = true;
  };
  const cancelHandle = (row: StockManagement.ListRows) => {
    drawerOpts.title = `取消预报(${row.waybillNum})`;
    drawerOpts.width = "1200px";
    drawerOpts.type = 1;
    drawerOpts.component = "CancelAdvance";
    drawerOpts.passData = row;
    drawerOpts.visible = true;
  };
  const makeInvoiceHandle = () => {
    if (!selectRows.value.length) return Message.error("请勾选运单!");
    if (selectRows.value.length > 1) return Message.error("只能勾选1条运单!");
    if (selectRows.value[0].makeInvoiceStatus === -2) return Message.error("只能操作未制作发票的数据!");
    drawerOpts.title = `制作发票`;
    drawerOpts.width = "1800px";
    drawerOpts.type = 1;
    drawerOpts.component = "MakeInvoice";
    drawerOpts.passData = selectRows.value[0];
    drawerOpts.visible = true;
  };
  // 修改渠道
  const modifyChannelHandle = () => {
    if (!selectRows.value.length) return Message.error("请勾选运单!");
    if (selectRows.value.length > 1) return Message.error("只能勾选1条运单!");
    dialogOpts.title = `修改渠道`;
    dialogOpts.width = "520px";
    dialogOpts.type = 1;
    dialogOpts.component = "ModifyChannel";
    dialogOpts.passData = selectRows.value[0];
    dialogOpts.visible = true;
  };
  // 修改品名
  const modifyProductNameHandle = () => {
    if (!selectRows.value.length) return Message.error("请勾选运单!");
    if (selectRows.value.length > 1) return Message.error("只能勾选1条运单!");
    if (selectRows.value[0].makeInvoiceStatus === -2) return Message.error("请修改运单发票内材质！");
    dialogOpts.title = `修改品名`;
    dialogOpts.width = "520px";
    dialogOpts.type = 1;
    dialogOpts.component = "ModifyProductName";
    dialogOpts.passData = selectRows.value[0];
    dialogOpts.visible = true;
  };
  // 修改材质
  const modifyMasterialHandle = () => {
    if (!selectRows.value.length) return Message.error("请勾选运单!");
    if (selectRows.value.length > 1) return Message.error("只能勾选1条运单!");
    if (selectRows.value[0].makeInvoiceStatus === -2) return Message.error("请修改运单发票内材质！");
    dialogOpts.title = `修改材质`;
    dialogOpts.width = "520px";
    dialogOpts.type = 1;
    dialogOpts.component = "ModifyMasterial";
    dialogOpts.passData = selectRows.value[0];
    dialogOpts.visible = true;
  };
  // 修改客户备注
  const modifyRemarkHandle = () => {
    if (!selectRows.value.length) return Message.error("请勾选运单!");
    dialogOpts.title = `修改客户备注`;
    dialogOpts.width = "520px";
    dialogOpts.type = 1;
    dialogOpts.component = "ModifyRemark";
    dialogOpts.passData = selectRows.value;
    dialogOpts.visible = true;
  };
  // 修改客户备注
  const modifyInnerRemarkHandle = () => {
    if (!selectRows.value.length) return Message.error("请勾选运单!");
    dialogOpts.title = `修改内部备注`;
    dialogOpts.width = "520px";
    dialogOpts.type = 2;
    dialogOpts.component = "ModifyRemark";
    dialogOpts.passData = selectRows.value;
    dialogOpts.visible = true;
  };
  // 手动拣货
  const handPickingOrderHandle = () => {
    if (!selectRows.value.length) return Message.error("请勾选运单!");
    if (selectRows.value.length > 1) return Message.error("只能勾选1条运单!");
    const row = selectRows.value[0];
    drawerOpts.title = `手动拣货/${row.waybillNum}/${row.customerName}`;
    drawerOpts.width = "1500px";
    drawerOpts.type = 1;
    drawerOpts.component = "PickingOrder";
    drawerOpts.passData = row;
    drawerOpts.visible = true;
  };
  // 取消运单
  const cancelShipmentHandle = () => {
    if (!selectRows.value.length) return Message.error("请勾选运单!");
    const ids = selectRows.value.map((t: any) => t.id);
    cancelBatchOrderShipmentApi(ids).then((res: any) => {
      const { code, data } = res;
      if (code === 200 && data === "取消成功") {
        Message.success("操作成功!");
        getData();
        // pageStateic();
      }
    });
  };
  // 打印
  const printLabelHandle = () => {
    if (!selectRows.value.length) return Message.error("请勾选运单!");
    loading.value = true;
    printLabelApi({ idList: selectRows.value.map((t: ClientAdvanceManagement.ListRows) => t.id), type: 2 })
      .then((res: any) => {
        if (res.headers["content-type"] === "application/json") {
          const reader = new FileReader(); //创建一个FileReader实例
          reader.readAsText(res.data, "utf-8"); //读取文件,结果用字符串形式表示
          reader.onload = () => {
            //读取完成后,**获取reader.result**
            const { message } = JSON.parse(reader.result as string);
            Message.error(message); //弹出错误提示
          };
        } else {
          const pdfUrl = window.URL.createObjectURL(res.data);
          printJs({ printable: pdfUrl, type: "pdf" });
        }
      })
      .finally(() => (loading.value = false));
  };
  // 下载标签    2合并下载
  const downloadLabelHandle = (buttonType: number | undefined) => {
    if (!selectRows.value.length) return Message.error("请勾选运单!");
    loading.value = true;
    printLabelApi({ idList: selectRows.value.map((t: ClientAdvanceManagement.ListRows) => t.id), type: 2, buttonType })
      .then((res: any) => {
        if (res.headers["content-type"] === "application/json") {
          const reader = new FileReader(); //创建一个FileReader实例
          reader.readAsText(res.data, "utf-8"); //读取文件,结果用字符串形式表示
          reader.onload = () => {
            //读取完成后,**获取reader.result**
            const { message } = JSON.parse(reader.result as string);
            Message.error(message); //弹出错误提示
          };
        } else {
          //判断推单状态
          if (res.headers["content-type"] === "application/pdf") {
            const { waybillNum, channelName, itemNumber } = selectRows.value[0];
            downloadFileByBlob(res.data, `${waybillNum}+${itemNumber}件+${channelName}.pdf`, "application/pdf");
          } else {
            downloadFileByBlob(res.data, "标签.zip");
          }
        }
      })
      .finally(() => (loading.value = false));
  };

  // 创建运单
  const createShipmentHandle = () => {
    if (!selectRows.value.length) return Message.error("请勾选运单!");
    pushOrdersTttxApi({ idList: selectRows.value.map((t: any) => t.id), status: activeKey.value }).then((res: any) => {
      const { code } = res;
      if (code === 200) {
        Message.success("操作成功!");
        searchHandle();
      }
    });
  };

  //批量导出
  const exportHandle = () => {
    const params = {
      ...getParams(),
      list: selectRows.value.length ? selectRows.value : [],
      statusList: activeKey.value === "-1" ? [1, 2, 3, 4] : [Number(activeKey.value)]
    };
    return stockManagementExportApi(params).then((res: any) => {
      const { code } = res;
      if (code === 200) {
        message.success("创建任务成功，请前往导出中心下载！");
      }
    });
  };

  // 发票导出
  const invoiceExportHandle = () => {
    if (!selectRows.value.length) return Message.error("请勾选运单!");
    const index = selectRows.value.findIndex((t: StockManagement.ListRows) => t.makeInvoiceStatus === -1);
    if (index !== -1) return Message.error("只能勾选已制作发票的运单!");
    dialogOpts.title = "发票导出";
    dialogOpts.width = "520px";
    dialogOpts.passData = selectRows.value;
    dialogOpts.component = "InvoiceExport";
    dialogOpts.visible = true;
  };
  //修改取件地址
  const modifyPickupAddressHandle = (row: StockManagement.ListRows) => {
    dialogOpts.width = "820px";
    dialogOpts.title = "修改取件地址";
    dialogOpts.type = 2;
    dialogOpts.passData = row;
    dialogOpts.component = "ModifyPickupAddress";
    dialogOpts.visible = true;
  };
  //修改取货时间
  const modifyTimeHandle = (row: StockManagement.ListRows) => {
    dialogOpts.width = "520px";
    dialogOpts.title = "修改期望取件时间";
    dialogOpts.type = 2;
    dialogOpts.passData = row;
    dialogOpts.component = "ModifyTime";
    dialogOpts.visible = true;
  };

  //合并报关
  const customsClearanceHandle = () => {
    if (selectRows.value.length < 2) return Message.error("至少勾选两条运单!");
    loading.value = true;
    return customsClearanceApi(selectRows.value.map((t: any) => t.id))
      .then((res: any) => {
        const { code } = res;
        if (code === 200) {
          Message.success("操作成功!");
          searchHandle();
        }
      })
      .finally(() => {
        loading.value = false;
      });
  };

  // 使用模版导出
  const templateExportHandle = () => {
    dialogOpts.title = `模版导出`;
    dialogOpts.width = "520px";
    dialogOpts.component = "TemplateExport";
    dialogOpts.type = 1;
    dialogOpts.passData = { searchForm: getParams(), selectRows: selectRows.value };
    dialogOpts.visible = true;
  };
  // 自定义模版导出
  const customExportHandle = () => {
    dialogOpts.title = `自定义模版导出`;
    dialogOpts.width = "800px";
    dialogOpts.component = "CustomExport";
    dialogOpts.type = 1;
    dialogOpts.passData = { searchForm: getParams(), selectRows: selectRows.value };
    dialogOpts.visible = true;
  };

  return {
    searchHandle,
    getData,
    editHandle,
    showHandle,
    changeTabHandle,
    cancelHandle,
    // pageStateic,
    makeInvoiceHandle,
    modifyChannelHandle,
    modifyProductNameHandle,
    modifyMasterialHandle,
    modifyRemarkHandle,
    modifyInnerRemarkHandle,
    handPickingOrderHandle,
    cancelShipmentHandle,
    printLabelHandle,
    downloadLabelHandle,
    createShipmentHandle,
    createWorkOrderHandle,
    exportHandle,
    invoiceExportHandle,
    modifyPickupAddressHandle,
    modifyTimeHandle,
    customsClearanceHandle,
    templateExportHandle,
    customExportHandle
  };
}
